<template>
  <!--表-->
  <nf-grid
    v-bind="gridMeta"
    :dataList="list"
    :selection="selection"
    size="small"
  >
  </nf-grid>
</template>

<script lang="ts">
  import { defineComponent, reactive, watch } from 'vue'
  import {
    getMetaDataState
  } from '../../../../lib-excel/main'

  import _gridMeta from './json/grid-table.json'

  interface IRow {
    tableID: string | number,
    tableName: string,
    cnName: string
  }
  interface ISelection {
    dataId: string | number, // 单选ID number 、string
    row: IRow, // 单选的数据对象 {}
    dataIds: Array<string | number>, // 多选ID []
    rows:  Array<IRow> // 多选的数据对象 []
  }

  export default defineComponent({
    name: 'nf-xls-table',
    props: {
    },
    setup(props, context) {
      const gridMeta = reactive(_gridMeta)

      const state = getMetaDataState()

      const { sheets, current } = state
      
      const list = reactive<ISelection[]>([])
      const selection = reactive({
        dataId: '', // 单选ID number 、string
        row: {}, // 单选的数据对象 {}
        dataIds: [], // 多选ID []
        rows: [] // 多选的数据对象 []
      })

      // 依据 sheet 加载里面的表
      watch(() => current.sheetName, (name) => {
        if (name !== '没有文件') {
          if (sheets[name]) {
            list.length = 0
            list.push(...sheets[name])
          }
        }
      })

      // 监听选择的表，设置字段
      watch(selection, () => {
        if (selection.dataId !== '') {
          state.current.table.tableID = selection.row.tableID
          state.current.table.tableName = selection.row.tableName
          state.current.table.cnName = selection.row.cnName
          state.current.table.cols.length = 0
          state.current.table.cols.push(...state.tables[selection.row.tableID].cols)
        } else {
          state.current.table.tableID = ''
          state.current.table.tableName = ''
          state.current.table.cnName = ''
          state.current.table.cols.length = 0
        }
       
      })

      return {
        selection,
        gridMeta,
        list
      }
    }
  })
</script>